<template>
  <div class="publish-container">
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
      <!-- 文章标题 -->
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入文章标题（最多50字）"
          maxlength="50"
          show-word-limit
        ></el-input>
      </el-form-item>

      <!-- 文章摘要 -->
      <el-form-item label="文章摘要" prop="summary">
        <el-input
          v-model="formData.summary"
          type="textarea"
          placeholder="请输入文章摘要（最多200字）"
          maxlength="200"
          show-word-limit
          :rows="4"
        ></el-input>
      </el-form-item>

      <!-- 所属频道 -->
      <el-form-item label="所属频道" prop="channelId">
        <el-select v-model="formData.channelId" placeholder="请选择频道" class="full-width">
          <el-option
            v-for="item in channelOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- 文章封面 -->
      <el-form-item label="文章封面">
        <div class="cover-upload">
          <div class="upload-container" @click="coverBtnClick">
            <div class="upload-placeholder" v-if="!formData.cover">
              <i class="iconfont-sys">&#xe6ee;</i>
              <div>点击上传封面图片</div>
            </div>
            <img v-else :src="formData.cover" class="cover-image" />
          </div>
        </div>
      </el-form-item>

      <!-- 发布时间 -->
      <el-form-item label="发布时间" prop="publishTime">
        <el-date-picker
          v-model="formData.publishTime"
          type="datetime"
          placeholder="请选择发布时间"
          class="full-width"
        ></el-date-picker>
      </el-form-item>

      <!-- 文章内容 -->
      <el-form-item label="文章内容" prop="content">
        <div>
          <ArtWangEditor
            v-model="formData.content"
            :uploadConfig="{ server: '/api/wemedia/common/upload' }"
          />
        </div>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交审核</el-button>
        <el-button @click="saveAsDraft">保存草稿</el-button>
      </el-form-item>
    </el-form>
    <el-drawer title="封面上传" v-model="drawerVisible">
      <el-tabs v-model="currentTab" class="demo-tabs" @tab-click="tabClick" style="height: 100%">
        <el-tab-pane
          label="本地上传"
          name="local"
          style="
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
          "
        >
          <el-upload
            action="/api/wemedia/common/upload"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
          >
            <!-- 有图片时显示预览 -->
            <div v-if="selectedimage" class="cover-preview">
              <img
                :src="selectedimage"
                class="cover-image"
                style="width: 100%; object-fit: cover"
              />
            </div>
            <!-- 没有图片时显示按钮 -->
            <el-button v-else type="primary" size="large">上传图片</el-button>
          </el-upload>
          <div
            style="display: flex; justify-content: center; margin-top: 20px"
            v-if="selectedimage"
          >
            <el-button type="primary" @click="confirmUpload">确定</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="我的素材" name="material" style="height: 100%">
          <div class="material-grid">
            <el-card
              v-for="item in materialList"
              :key="item.id"
              class="material-item"
              :body-style="{ padding: '0px' }"
              @click="selectMaterial(item)"
            >
              <el-image :src="item.url" fit="cover" class="material-image" />
            </el-card>
          </div>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="queryParams.page"
              v-model:page-size="queryParams.size"
              :total="total"
              :page-sizes="[10, 20, 30, 40]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import type { FormInstance, FormRules, TabsPaneContext } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { WmChannelItem, WmNewsParams } from '@/typings/wmNews'
  import { wmNewsApi } from '@/api/wmNewsApi'
  import { WmMaterialService } from '@/api/wmMaterialApi'
  import { WmMaterialItem, WmMaterialParams } from '@/typings/wmMaterial'

  // 表单引用
  const formRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive<WmNewsParams>({
    title: '',
    summary: '',
    channelId: '',
    cover: '',
    status: 0,
    publishTime: new Date().toISOString(),
    content: ''
  })

  // 表单验证规则
  const rules = reactive<FormRules>({
    title: [
      { required: true, message: '请输入文章标题', trigger: 'blur' },
      { max: 50, message: '标题不能超过50个字符', trigger: 'blur' }
    ],
    summary: [
      { required: true, message: '请输入文章摘要', trigger: 'blur' },
      { max: 200, message: '摘要不能超过200个字符', trigger: 'blur' }
    ],
    channelId: [{ required: true, message: '请选择所属频道', trigger: 'change' }],
    content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
  })

  // 频道选项
  const channelOptions = ref<WmChannelItem[]>([])

  const getChannel = async () => {
    const res = await wmNewsApi.getChannelList({
      status: 1,
      isDefault: 1
    })
    channelOptions.value = res
  }

  onMounted(() => {
    getChannel()
  })

  const selectedimage = ref('')

  // 处理封面图片变化
  const handleCoverSuccess = async (response: any) => {
    console.log('response', response)
    selectedimage.value = response.data[0]
  }

  // 确认上传
  const confirmUpload = () => {
    formData.cover = selectedimage.value
    drawerVisible.value = false
  }

  // 提交表单
  const submitForm = async () => {
    console.log('formData', formData)
    if (!formRef.value) return

    await formRef.value.validate((valid: boolean) => {
      if (valid) {
        ElMessage.success('提交成功')
        console.log('表单数据:', formData)
      } else {
        ElMessage.error('请完善表单信息')
      }
    })
  }

  // 保存为草稿
  const saveAsDraft = () => {
    ElMessage.success('已保存为草稿')
    console.log('草稿数据:', formData)
  }

  // 抽屉是否可见
  const drawerVisible = ref(false)

  // 封面上传按钮点击
  const coverBtnClick = () => {
    drawerVisible.value = true
  }

  // 封面上传选项卡切换
  const currentTab = ref('local')

  // 封面上传选项卡切换事件
  const tabClick = (tab: TabsPaneContext) => {
    currentTab.value = tab.props.name as string
    if (currentTab.value === 'material') {
      loadMaterialList()
    }
  }

  // 查询参数
  const queryParams = ref<WmMaterialParams>({
    page: 1,
    size: 10,
    isCollection: 0
  })

  const materialList = ref<WmMaterialItem[]>([])
  const total = ref(0)

  // 加载素材列表
  const loadMaterialList = async () => {
    const res = await WmMaterialService.getMaterialList(queryParams.value)
    materialList.value = res.records
    total.value = res.total
  }

  // 分页大小改变
  const handleSizeChange = (val: number) => {
    queryParams.value.size = val
    loadMaterialList()
  }

  // 页码改变
  const handleCurrentChange = (val: number) => {
    queryParams.value.page = val
    loadMaterialList()
  }

  // 选择素材
  const selectMaterial = (item: WmMaterialItem) => {
    formData.cover = item.url
    drawerVisible.value = false
  }
</script>

<style scoped lang="scss">
  .publish-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  }

  .full-width {
    width: 100%;
  }

  .cover-upload {
    width: 100%;

    .upload-container {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 360px;
      height: 180px;
      overflow: hidden;
      cursor: pointer;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;

      &:hover {
        border-color: var(--el-color-primary);
      }
    }

    .upload-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      color: #8c939d;

      .iconfont-sys {
        margin-bottom: 8px;
        font-size: 32px;
      }
    }

    .cover-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;

    .editor-toolbar {
      padding: 8px;
      background-color: #f5f7fa;
      border-bottom: 1px solid #dcdfe6;
    }
  }

  .material-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }

  .material-item {
    position: relative;
    overflow: hidden;
  }

  .material-image {
    width: 100%;
    height: 150px;
    object-fit: cover;
  }

  .material-actions {
    display: flex;
    justify-content: center;
    padding: 10px;
    background-color: #fff;
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
</style>

<style scoped></style>
